<?php
set_time_limit(0);

include_once('lib/config.php');

$redis = new Redis();
$redis->connect('198.56.144.195',"6379");  //php客户端设置的ip及端口
if(!$redis) die('redis connect fail');

$tree_key = 'zdb_image:';

$limit = 5000;
while($limit--) {
  $stop = $redis->get('STOP_MH_PIC_QUEUE');
  if($stop) {
    die('stop');
  }

  $queue = $redis->lPop(MH_QUEUE);
  if ($queue) {
    $tmp = explode('$$', $queue);
    $news_id = $tmp[0];
    $id   = $tmp[1];
    $k    = $tmp[2];
    $link = $tmp[3];
    
    //$pin      = addcslashes($pin, ',! ');
    $localDir = dirname(__FILE__).'/Public/mh/'.$news_id;
    $sname = getSaveName($link, $id, $k);
    @mkdir($localDir);

    $filepath = $localDir.'/'.$sname;
    $cmd = "wget --limit-rate=1000k --continue --timeout=120 --tries=5 --no-clobber --no-host-directories '".$link."' -O '".$filepath."'";
    $result = shell_exec($cmd);

    clearstatcache();
    $filesize = (int) filesize($filepath);

    if(!file_exists($filepath) || $filesize < 5000) {
      $redis->lPush($tree_key.MH_DOWN_FAIL, $queue);
      
      //$redis->rPush(MH_QUEUE, $queue);
    
      $redis->select(2);
      $redis->hSet($news_id, $id.'_'.$k, $queue);
      $redis->select(0);
      if(file_exists($filepath)) @unlink($filepath);
    } else {
      $redis->lPush($tree_key.MH_DOWN_SUCCESS, date('Y-m-d H:i:s').':'.$news_id.'/'.$sname);
      $redis->select(0);
    }

    usleep(1000*100);
    //echo date('Y-m-d H:i:s'). ' # '.$queue.' # '.$pin.'/'.$sname;
    //echo "\n";
  } else {
    //echo 'down empty'."\n";
    sleep(1);
  }

  //die();
}
